package com.atguigu.gulimall.cart.interceptor;

import com.atguigu.common.constant.SessionAttrKeyConstant;
import com.atguigu.common.vo.MemberEntity;
import com.atguigu.gulimall.cart.to.UserInfoTo;
import com.atguigu.gulimall.cart.constant.CartConstant;
import org.apache.commons.lang.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 拦截器逻辑：业务执行之前，判断是否登录，若登录则封装用户信息，将标识位设置为true，
 * postHandler就不再设置作用域和有效时间，否则为其创建一个user-key
 * 注意细节：整合SpringSession之后，Session获取数据都是从Redis中获取的
 * 使用ThreadLocal，解决线程共享数据问题，方便同一线程共享UserInfoTo
 */
@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    // 业务逻辑执行前,此方法执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        // 整合了spring-session之后,通过装饰者模式,其实session都是从redis中获取了
        HttpSession session = request.getSession();
        MemberEntity memberEntity = (MemberEntity) session.getAttribute(SessionAttrKeyConstant.LOGIN_USER);
        if (memberEntity!=null){
            userInfoTo.setUserId(memberEntity.getId());
        }
        // 遍历cookies
        Cookie[] cookies = request.getCookies();
        if(cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    // 封装user-key
                    userInfoTo.setUserKey(cookie.getValue());
                    // 设置标识位
                    userInfoTo.setTempUser(true);
                }
            }
        }
        // 没有user-key则设置一个
        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            String key = UUID.randomUUID().toString();
            userInfoTo.setUserKey(key);
        }
        threadLocal.set(userInfoTo);
        return true;
    }

    // 业务逻辑执行后,此方法执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if(!userInfoTo.getTempUser()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            // 设置作用域
            cookie.setDomain("gulimall.com");
            // 设置作用时间,单位为second
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            // 浏览器添加cookie
            response.addCookie(cookie);
        }


    }

}
